<?php

namespace AlibabaCloud\SDK\Sample;

use AlibabaCloud\SDK\Iot\V20180120\Iot;
use \Exception;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Utils\Utils;
use AlibabaCloud\Tea\Tea;

use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Iot\V20180120\Models\QueryDevicePropertyDataRequest;
use AlibabaCloud\SDK\Iot\V20180120\Models\SetDevicePropertyRequest;
use AlibabaCloud\SDK\Iot\V20180120\Models\QueryDeviceInfoRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;


class Sample 
{
    public static function formatToTimeStamp($time)
    {
        if ($time) {
            if (is_numeric($time)) {
                $timestamp = strtotime("1900-01-01") + ($time - 2) * 24 * 60 * 60;
            } else {
                // 将年月日的格式替换成-
                $time = str_replace("年", "-", $time);
                $time = str_replace("月", "-", $time);
                $time = str_replace(".", "-", $time);
                $time = str_replace("/", "-", $time);
                $time = str_replace("日", "", $time);
                // 检查最后一个字符是否为-, 若为- 补01作为日
                if (substr($time, -1) == '-') {
                    $time .= '01';
                }
                $timestamp = strtotime($time);
            }
            return $timestamp;
        }
        return 0;
    }
    /** 
     * 返回特定时间的毫秒时间戳
     * @param string $time 特定时间，格式要求(Y-m-d H:i:s)
     * @return integer $msectime 毫秒时间戳(13位)
     */
    public static function formatToMSecTimeStamp($time)
    {
        $msec = 0;
        $sec = Sample::formatToTimeStamp($time);
        $msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
        return $msectime;
    }
    /**
     * 使用AK&SK初始化Client
     * @param string $accessKeyId
     * @param string $accessKeySecret
     */
    public static function createClient($accessKeyId, $accessKeySecret){
        $config = new Config([]);
        $config->accessKeyId = $accessKeyId;
        $config->accessKeySecret = $accessKeySecret;
        $config->endpoint = "iot.cn-shanghai.aliyuncs.com";
        return new Iot($config);
    }
    /**
     * QueryDevicePropertyData：产品管理类API，用于查询指定产品指定属性的历史信息
     * 需设备在线才可使用
     */
    public function queryDevicePropertyData($accessKey,$accessKeySecret,$productKey,$iotInstanceId,$productName,$pagesize=10,$asc=1,$identifier,$Tstart,$Tend)
    {
        $client = self::createClient("${accessKey}", "${accessKeySecret}");
        $start=Sample::formatToMSecTimeStamp($Tstart);
        $end=Sample::formatToMSecTimeStamp($Tend);
        $request = new QueryDevicePropertyDataRequest([
            "iotInstanceId" => $iotInstanceId,
            "productKey" => $productKey,
            "deviceName" => $productName,
            "startTime" => $start,
            "endTime" => $end,
            "pageSize" => $pagesize,
            "asc" => $asc,
            "identifier" => $identifier
        ]);
        $runtime = new RuntimeOptions([]);
        try {
            $response=$client->QueryDevicePropertyDataWithOptions($request, $runtime);
            echo(json_encode(Utils::toJSONString(Tea::merge($response))));
        }
        catch (Exception $error) {
            if (!($error instanceof TeaError)) {
                $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
            }
            echo(json_encode($error->message));
        }
    }
    /**
     * SetDeviceProperty：用于设定指定产品指定属性的历史信息期望值
     * 需设备在线才可使用，items格式为json string
     */
    public function setDeviceProperty($accessKey,$accessKeySecret,$productKey,$iotInstanceId,$productName,$items)
    {
        $client = self::createClient("${accessKey}", "${accessKeySecret}");
        $request = new SetDevicePropertyRequest([
            "iotInstanceId" => $iotInstanceId,
            "productKey" => $productKey,
            "deviceName" => $productName,
            "items" => $items,
        ]);
        $runtime = new RuntimeOptions([]);
        try {
            $response=$client->setDevicePropertyWithOptions($request, $runtime);
            echo(json_encode(Utils::toJSONString(Tea::merge($response))));
        }
        catch (Exception $error) {
            if (!($error instanceof TeaError)) {
                $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
            }
            echo(json_encode($error->message));
        }
    }
    /**
     * queryDeviceInfo:查询指定设备的基本信息（设备ID、设备证书和备注名称）
     */
    public function queryDeviceInfo($accessKey,$accessKeySecret,$productKey,$iotInstanceId,$productName)
    {
        $client = self::createClient("${accessKey}", "${accessKeySecret}");
        $request = new QueryDeviceInfoRequest([
            "iotInstanceId" => $iotInstanceId,
            "productKey" => $productKey,
            "deviceName" => $productName,
        ]);
        $runtime = new RuntimeOptions([]);
        try {
            $response=$client->QueryDeviceInfoWithOptions($request, $runtime);
            echo(json_encode(Utils::toJSONString(Tea::merge($response))));
        }
        catch (Exception $error) {
            if (!($error instanceof TeaError)) {
                $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
            }
            echo(json_encode($error->message));
        }
    }
}
$path = __DIR__ . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . 'vendor' . \DIRECTORY_SEPARATOR . 'autoload.php';
if (file_exists($path)) {
    require_once $path;
}
//Sample::queryDevicePropertyData("accessKey","accessKeySecret","productKey","iotInstanceId","productName","pagesize","asc(result order)","identifier","Tstart(Start time)","Tend(End time)");
//Sample::setDeviceProperty("accessKey","accessKeySecret","productKey","iotInstanceId","productName","items");
//Sample::QueryDeviceInfo("accessKey","accessKeySecret","productKey","iotInstanceId","productName");